package com.sunshine.lnuplus.view

import android.app.Activity
import android.app.DatePickerDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.TypedValue
import android.view.LayoutInflater
import android.widget.SeekBar
import androidx.appcompat.widget.AppCompatEditText
import androidx.fragment.app.FragmentManager
import androidx.preference.CheckBoxPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SeekBarPreference
import com.google.android.material.textfield.TextInputLayout
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.callback.TimetableSettingCallBack
import com.sunshine.lnuplus.model.InitData
import com.sunshine.lnuplus.ui.activity.LessonTimeActivity
import com.sunshine.lnuplus.utils.DateUtils
import com.sunshine.lnuplus.utils.TagHelper
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.dialog_pick_color.view.*

class TimetableSettingView : PreferenceFragmentCompat(), Preference.OnPreferenceChangeListener,
    Preference.OnPreferenceClickListener {

    private lateinit var callback: TimetableSettingCallBack
    private lateinit var sp: SharedPreferences
    private lateinit var edit: SharedPreferences.Editor

    fun init(callback: TimetableSettingCallBack){
        this.callback = callback
    }
    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.setting_timetable, rootKey)
        sp = context?.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE)!!
        edit = sp.edit()

        preferenceManager.findPreference<SeekBarPreference>("weeks_count")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
            summary = "${this.value}周"
        }
        preferenceManager.findPreference<SeekBarPreference>("every_day_count")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
            summary = "${this.value}节"
        }
        preferenceManager.findPreference<SeekBarPreference>("text_size")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
            summary = "${this.value}sp"
        }
        preferenceManager.findPreference<SeekBarPreference>("height")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
            summary = "${this.value}dp"
        }
        preferenceManager.findPreference<SeekBarPreference>("alpha")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
            summary = "${this.value.toFloat()/255*100}%"
        }
        preferenceManager.findPreference<SeekBarPreference>("radius")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
            summary = "${this.value}"
        }
        preferenceManager.findPreference<SeekBarPreference>("width_distance")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
            summary = "${this.value}dp"
        }
        preferenceManager.findPreference<SeekBarPreference>("height_distance")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
            summary = "${this.value}dp"
        }
        preferenceManager.findPreference<SeekBarPreference>("padding")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
            summary = "${this.value}dp"
        }
        preferenceManager.findPreference<SeekBarPreference>("time_text_size")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
            summary = "${this.value}sp"
        }
        preferenceManager.findPreference<CheckBoxPreference>("show_weekend")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
        }
        preferenceManager.findPreference<CheckBoxPreference>("show_not_in_this_week")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
        }
        preferenceManager.findPreference<CheckBoxPreference>("detail_show_not_in_this_week")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
        }
        preferenceManager.findPreference<CheckBoxPreference>("show_teacher")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
        }
        preferenceManager.findPreference<CheckBoxPreference>("show_time")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
        }
        preferenceManager.findPreference<CheckBoxPreference>("sunday_first")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
        }
        preferenceManager.findPreference<CheckBoxPreference>("text_left")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
        }
        preferenceManager.findPreference<CheckBoxPreference>("next_day")?.apply {
            onPreferenceChangeListener = this@TimetableSettingView
            preferenceManager.findPreference<Preference>("next_day_time")?.isEnabled = this.isChecked
        }
        preferenceManager.findPreference<Preference>("next_day_time")?.apply {
            onPreferenceClickListener = this@TimetableSettingView
            summary = "当前指定时间：${InitData.lessonStyle.nextDayTime}点"
        }
        preferenceManager.findPreference<Preference>("begin_date")?.apply {
            onPreferenceClickListener = this@TimetableSettingView
            summary = "${(sp.getInt("start_month", if(DateUtils.month > 8) 8 else 2)).plus(1)}月${sp.getInt("start_day", 1)}日"
        }
        preferenceManager.findPreference<Preference>("text_color")?.apply {
            onPreferenceClickListener = this@TimetableSettingView
        }
        preferenceManager.findPreference<Preference>("date_and_time_text_color")?.apply {
            onPreferenceClickListener = this@TimetableSettingView
        }
        preferenceManager.findPreference<Preference>("date_color")?.apply {
            onPreferenceClickListener = this@TimetableSettingView
        }
        preferenceManager.findPreference<Preference>("lesson_time")?.apply {
            onPreferenceClickListener = this@TimetableSettingView
        }
    }

    override fun onPreferenceChange(preference: Preference?, newValue: Any?): Boolean {
        when(preference?.key){
            "weeks_count" -> {
                preference.summary = "${newValue}周"
                InitData.lessonStyle.weekCount = newValue as Int
                callback.onChanged()
            }
            "every_day_count" -> {
                preference.summary = "${newValue}节"
                InitData.lessonStyle.count = newValue as Int
                callback.onChanged()
            }
            "text_size" -> {
                preference.summary = "${newValue}sp"
                InitData.lessonStyle.textSize = newValue as Int
                callback.onChanged()
            }
            "height" -> {
                preference.summary = "${newValue}dp"
                InitData.lessonStyle.height = newValue as Int
                if(newValue < 150) Toasty.info(context!!, "调节过小可能引起界面错乱，请自行判断").show()
                callback.onChanged()
            }
            "alpha" -> {
                preference.summary = "${(newValue as Int).toFloat()/255*100}%"
                InitData.lessonStyle.alpha = newValue
                callback.onChanged()
            }
            "radius" -> {
                preference.summary = "$newValue"
                InitData.lessonStyle.round = newValue as Int
                callback.onChanged()
            }
            "width_distance" -> {
                preference.summary = "${newValue}dp"
                InitData.lessonStyle.widthDistant = newValue as Int
                callback.onChanged()
            }
            "height_distance" -> {
                preference.summary = "${newValue}dp"
                InitData.lessonStyle.heightDistant = newValue as Int
                callback.onChanged()
            }
            "padding" -> {
                preference.summary = "${newValue}dp"
                InitData.lessonStyle.padding = newValue as Int
                callback.onChanged()
            }
            "time_text_size" -> {
                preference.summary = "${newValue}sp"
                InitData.lessonStyle.timeTextSize = newValue as Int
                callback.onChanged()
            }
            "show_weekend" -> {
                InitData.lessonStyle.showWeekend = newValue as Boolean
                callback.onChanged()
            }
            "show_not_in_this_week" -> {
                InitData.lessonStyle.showNotInThisWeek = newValue as Boolean
                callback.onChanged()
            }
            "detail_show_not_in_this_week" -> {
                InitData.lessonStyle.detailShowNotInThisWeek = newValue as Boolean
                callback.onChanged()
            }
            "show_teacher" -> {
                InitData.lessonStyle.showTeacher = newValue as Boolean
                callback.onChanged()
            }
            "show_time" -> {
                InitData.lessonStyle.showTime = newValue as Boolean
                callback.onChanged()
            }
            "sunday_first" -> {
                InitData.lessonStyle.sundayFirst = newValue as Boolean
                callback.onChanged()
            }
            "text_left" -> {
                InitData.lessonStyle.textLeft = newValue as Boolean
                callback.onChanged()
            }
            "next_day" -> {
                val boolean = newValue as Boolean
                InitData.lessonStyle.nextDay = boolean
                preferenceManager.findPreference<Preference>("next_day_time")?.isEnabled = boolean
                callback.onChanged()
            }
        }
        return true
    }

    override fun onPreferenceClick(preference: Preference?): Boolean {
        when(preference?.key){
            "begin_date" -> {
                val sp = context!!.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE)
                val edit = sp.edit()
                val month = sp.getInt("start_month", if(DateUtils.month > 8) 8 else 2)
                val day = sp.getInt("start_day", 1)
                val datePickerDialog = DatePickerDialog(context!!,
                    DatePickerDialog.OnDateSetListener { _, _, month, dayOfMonth ->

                        edit.apply{
                            putInt("start_month", month)
                            putInt("start_day", dayOfMonth)
                            apply()
                        }
                        InitData.lessonStyle.startMonth = month
                        InitData.lessonStyle.startDay = dayOfMonth
                        preference.summary = "${month+1}月${dayOfMonth}日"
                        Toasty.success(context!!, "设置成功~").show()
                        callback.onChanged()
                    }, DateUtils.year, month, day
                )
                datePickerDialog.show()
            }
            "text_color" -> {
                val view = LayoutInflater.from(context).inflate(R.layout.dialog_pick_color, null, false)
                var tempColor = ""
                val pickColor = DialogWithView.newInstance(
                    view,
                    "请选择课程格子文字颜色",
                    false,
                    DialogInterface.OnClickListener { _, _ ->
                        val edit = context!!.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE).edit()
                        edit.apply{
                            putString("text_color", tempColor)
                            apply()
                        }
                        InitData.lessonStyle.textColor = tempColor
                        callback.onChanged()
                    },
                    null)
                pickColor.show(childFragmentManager, "pickColor")
                view.color_pick_view.setOnColorChangeListener {
                    tempColor = String.format("%08x",it)
                    tempColor = "#" + tempColor.substring(2, tempColor.length)
                }
            }

            "date_and_time_text_color" -> {
                val view = LayoutInflater.from(context).inflate(R.layout.dialog_pick_color, null, false)
                var tempColor = ""
                val pickColor = DialogWithView.newInstance(
                    view,
                    "请选择时间和日期文字颜色",
                    false,
                    DialogInterface.OnClickListener { _, _ ->
                        val edit = context!!.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE).edit()
                        edit.apply{
                            putString("date_and_time_text_color", tempColor)
                            apply()
                        }
                        InitData.lessonStyle.dateAndTimeTextColor = tempColor
                        callback.onChanged()
                    },
                    null)
                pickColor.show(childFragmentManager, "pickColor")
                view.color_pick_view.setOnColorChangeListener {
                    tempColor = String.format("%08x",it)
                    tempColor = "#" + tempColor.substring(2, tempColor.length)
                }
            }
            "date_color" -> {
                val view = LayoutInflater.from(context).inflate(R.layout.dialog_pick_color, null, false)
                var tempColor = ""
                val pickColor = DialogWithView.newInstance(
                    view,
                    "请选择日期栏“今日”指示按钮颜色",
                    false,
                    DialogInterface.OnClickListener { _, _ ->
                        val edit = context!!.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE).edit()
                        edit.apply{
                            putString("date_color", tempColor)
                            apply()
                        }
                        InitData.lessonStyle.dateColor = tempColor
                        callback.onChanged()
                    },
                    null)
                pickColor.show(childFragmentManager, "pickColor")
                view.color_pick_view.setOnColorChangeListener {
                    tempColor = String.format("%08x",it)
                    tempColor = "#" + tempColor.substring(2, tempColor.length)
                }
            }
            "lesson_time" -> {
                startActivityForResult(Intent(context!!, LessonTimeActivity::class.java), TagHelper.TIMETABLEVIEW)
            }
            "next_day_time" -> {
                val view = LayoutInflater.from(context).inflate(R.layout.dialog_calender_time, null, false)
                view.findViewById<TextInputLayout>(R.id.til_count_down_time).hint = "输入范围0~23"
                val dialog = DialogWithView.newInstance(
                    view,
                    "请输入指定时间",
                    false,
                    DialogInterface.OnClickListener { _, _ ->
                        try {
                            val time = view.findViewById<AppCompatEditText>(R.id.edit_calender_time).text.toString().toInt()
                            if(time < 0 || time > 23){
                                Toasty.error(context!!, "输入有问题呀~").show()
                            }else{
                                val preference = preferenceManager.findPreference<Preference>("next_day_time")
                                preference?.summary = "当前指定时间：${time}点"
                                edit.putInt("next_day_time", time)
                                edit.apply()
                                InitData.lessonStyle.nextDayTime = time
                            }
                        }catch (e: Exception){
                            Toasty.error(context!!, "输入有问题呀~").show()
                        }

                    },
                    null)
                dialog.show(childFragmentManager, "")
            }
        }
        return true
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == TagHelper.TIMETABLEVIEW){
            if(resultCode == Activity.RESULT_OK){
                callback.onChanged()
            }
        }
    }

}